package com.vadmin.vadminjava.service;

import com.alibaba.fastjson.JSONObject;
import com.ijpay.wxpay.WxPayApi;
import com.vadmin.vadminjava.common.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

import static com.ijpay.core.enums.RequestMethod.POST;
import static com.ijpay.wxpay.enums.WxDomain.CHINA;
import static com.vadmin.vadminjava.common.WxCouponUtils.*;

/* ***********************************************************
 *
 * 微信的卡劵接口：这是代金券的（目前应该不使用这个）
 *
 * **********************************************************/
@Component
public class WxCouponCashService {

	org.slf4j.Logger logger = LoggerFactory.getLogger(WxCouponCashService.class.getName());
	String           KEY_PATH;


	@Autowired
	WxCouponUtils wxCouponUtils;


	/**
	 * 激活代金券
	 *
	 * @description:
	 * @param:
	 * @return:
	 * @author
	 * @date: 2022/3/9 17:09
	 */
	public Map<String, Object> activationCouponT(String stockId) throws Exception {
		String              requestJson     = "{\"stock_creator_mchid\":\"" + MCH_ID + "\"}";
		String              urlSuffix       = "/v3/marketing/favor/stocks/" + stockId + "/start";
		Map<String, Object> stringObjectMap = WxPayApi.v3Execution(POST, CHINA.toString(), urlSuffix, MCH_ID, SERIAL_NO, KEY_PATH, requestJson);

		String status = stringObjectMap.get("status") + "";
		if (Integer.parseInt(status) == 200) {
			logger.info("激活成功:{} {}", stockId, status);
		} else {
			logger.info("激活成失败:{} {} {}", stockId, status, stringObjectMap);
		}

		return stringObjectMap;
	}

	/**
	 * 发放代金卷
	 *
	 * @description:
	 * @param:
	 * @return:
	 * @author
	 * @date: 2022/3/9 14:23
	 */
	public Map<String, Object> sendCoupon() throws Exception {
		String outRequestNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + System.currentTimeMillis();
		String requestJson = "{"
				+ "\"stock_id\": \"" + "16275347" + "\","
				+ "\"out_request_no\": \"" + outRequestNo + "\","
				+ "\"appid\": \"" + "wx35839eba72c12a73" + "\","
				+ "\"stock_creator_mchid\": \"" + "1622221291" + "\""
				+ "}";
		String              urlSuffix       = "/v3/marketing/favor/users/" + "oqGpx6BpNgk_Fftn7Xa1-2-WNSok" + "/coupons";
		Map<String, Object> stringObjectMap = WxPayApi.v3Execution(POST, CHINA.toString(), urlSuffix, "1622221291", SERIAL_NO, KEY_PATH, requestJson);
		logger.info("返回消息：{}", stringObjectMap);
		return stringObjectMap;
	}


	/**
	 * 创建代金券
	 *
	 * @description:
	 * @param:
	 * @return:
	 * @author
	 * @date: 2022/3/9 14:23
	 */
	public static String createCoupon(JSONObject coupon) {
		// 面额和门槛(单位都是分)

		// 这个值可以随意创建，只要保证唯一即可（不用在意我的创建方法）
		// 商户创建批次凭据号（格式：商户id+日期+流水号），可包含英文字母，数字，|，_，*，-等内容，不允许出现其他不合法符号，商户侧需保持唯一性 (9856886520200811174644kk6tclE)
		String outRequestNo = System.currentTimeMillis() + ThreadLocalRandom.current().nextInt(100000) + "";

		String info = "{\n" +
				"  \"stock_name\": \"" + coupon.getString("stockName") + "\",\n" +
				"  \"comment\": \"卓恩\",\n" +
				"  \"belong_merchant\": \"" + MCH_ID + "\",\n" +
				"  \"available_begin_time\":\"" + getRfc3339(coupon.getDate("beginTimestamp")) + "\",\n" +
				"  \"available_end_time\":\"" + getRfc3339(coupon.getSqlDate("ndTimestamp")) + "\",\n" +
				"  \"stock_use_rule\": {\n" +
				"    \"max_coupons\": " + coupon.getString("maxCoupons") + ",\n" +
				"    \"max_amount\": " + (BigDecimalUtils.mul(coupon.getString("maxCoupons"), coupon.getString("couponAmount")).toPlainString()) + ",\n" +
				"    \"max_coupons_per_user\": " + coupon.getString("maxCouponsPerUser") + ",\n" +
				"    \"natural_person_limit\": false,\n" +
				"    \"prevent_api_abuse\": false\n" +
				"  },\n" +
				"  \"pattern_info\": {\n" +
				"    \"description\": \"" + coupon.getString("stockName") + "\",\n" +
				"    \"merchant_logo\": \"https://qpic.cn/xxx\",\n" +
				"    \"merchant_name\": \"微信支付\",\n" +
				"    \"background_color\": \"COLOR020\",\n" +
				"    \"coupon_image\": \"https://qpic.cn/xxx\"\n" +
				"  },\n" +
				"  \"coupon_use_rule\": {\n" +
				"\n" +
				"    \"fixed_normal_coupon\": {\n" +
				"      \"coupon_amount\": " + coupon.getString("couponAmount") + ",\n" +
				"      \"transaction_minimum\": " + coupon.getString("transactionMinimum") + "\n" +
				"    },\n" +
				"\n" +
				"    \"trade_type\": [\"OTHER\",\"APPPAY\"],\n" +
				"    \"combine_use\": false,\n" +
				"    \"available_merchants\": [\n" +
				"      \"" + MCH_ID + "\"" +
				"    ]\n" +
				"  },\n" +
				"  \"no_cash\": true,\n" +
				"  \"stock_type\": \"NORMAL\",\n" +
				"  \"out_request_no\": \"" + System.currentTimeMillis() + "\"\n" +
				"}";
		return info;

	}


}
